# -*-coding:utf-8-*-
'''
沙箱环境	http://gw.api.tbsandbox.com/router/rest	https://gw.api.tbsandbox.com/router/rest
正式环境	http://gw.api.taobao.com/router/rest	https://eco.taobao.com/router/rest
海外环境	http://api.taobao.com/router/rest	    https://api.taobao.com/router/rest

短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，允许每分钟1条，累计每小时7条。
短信通知，使用同一签名、同一模板，对同一手机号发送短信通知，允许每天50条（自然日）。
'''
import time, hmac, json
from tornado.httpclient import HTTPClient, HTTPRequest
from urllib import urlencode
import sys

sys.path.append('..')
import settings

import logging

# from tornado.options import define, options
# options.parse_command_line()
# 在 tornado 环境下使用以下两行即可，因为 tornado 对 root logger 做了配置(如上两行起的作用)
logger = logging.getLogger()


# logger.setLevel(logging.DEBUG)


def url_compose(query=None):
    if query is None:
        return settings.TOP['gateway']
    else:
        return '%s?%s' % (settings.TOP['gateway'], query)


def __http_method(method, body=None, query=None):
    url = settings.TOP['gateway']
    if query is not None:
        url += '?%s' % query
    if body is not None:
        body = urlencode(body)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    http_request = HTTPRequest(url, method=method, body=body, headers=headers)
    http_client = HTTPClient()
    return http_client.fetch(http_request, raise_error=False)


def http_post(body, query=None):
    return __http_method('POST', body, query)


# http://open.taobao.com/docs/doc.htm?spm=a3142.7395905.4.22.80kC3e&articleId=101617&docType=1&treeId=1
class Topnado(object):
    # def __init__(self):
    #     self.appkey = settings.TOP['alidayu']['appkey']
    #     self.secret = settings.TOP['alidayu']['secret']

    def __build_common_params(self, app, sign_method='hmac'):
        params = {}
        params['app_key'] = app.get_alidayu_app_key()
        params['sign_method'] = sign_method
        params['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
        params['format'] = 'json'
        params['v'] = '2.0'
        return params

    def send_sms(self, app, to, sign_name, temp_code, temp_param, cookie=None):
        params = self.__build_common_params(app)
        params['method'] = 'alibaba.aliqin.fc.sms.num.send'
        params['sms_type'] = 'normal'
        if cookie is not None: params['extend'] = cookie
        params['sms_free_sign_name'] = sign_name
        params['sms_template_code'] = temp_code
        params['sms_param'] = temp_param
        params['rec_num'] = to
        keys = params.keys()
        keys.sort()
        params_string = ''
        for key in keys:
            params_string += key + str(params[key])
        # print 'params_string: %s' % params_string
        # digestmod default to hashlib.md5
        h = hmac.new(app.get_alidayu_secret(), params_string)
        params['sign'] = h.hexdigest().upper()
        # print 'sign: %s' % params['sign']
        '''
        {"error_response":{"code":15,"msg":"Remote service error","sub_code":"isv.BUSINESS_LIMIT_CONTROL","sub_msg":"触发业务流控","request_id":"3dp4r24z70cz"}}
        {"alibaba_aliqin_fc_sms_num_send_response":{"result":{"err_code":"0","model":"106888774525^1109310988770","success":true},"request_id":"3i4275gnh7f2"}}
        '''
        response = http_post(params)
        logger.debug('to: %s, response: %s' % (to, response.body))
        response = json.loads(response.body)
        if response.has_key('error_response'):
            return False, response['error_response']['sub_msg']
        else:
            return True, ''

    def send_register_code(self, app, to, code, cookie=None):
        sign_name = app.get_alidayu_sms_sign_name()
        temp_code = app.get_alidayu_sms_temp_code('register_code')
        temp_param = {'code': '%d' % code, 'product': app.get_name()}
        temp_param = json.dumps(temp_param, ensure_ascii=False)
        return self.send_sms(app, to, sign_name, temp_code, temp_param, cookie)

    def send_reset_password_code(self, app, to, code, cookie=None):
        sign_name = app.get_alidayu_sms_sign_name()
        temp_code = app.get_alidayu_sms_temp_code('reset_password_code')
        temp_param = {'code': '%d' % code, 'product': app.get_name()}
        temp_param = json.dumps(temp_param)
        return self.send_sms(app, to, sign_name, temp_code, temp_param, cookie)

    def send_change_phone_code(self, app, to, code, cookie=None):
        sign_name = app.get_alidayu_sms_sign_name()
        temp_code = app.get_alidayu_sms_temp_code('change_phone_code')
        temp_param = {'code': '%d' % code, 'product': app.get_name()}
        temp_param = json.dumps(temp_param)
        return self.send_sms(app, to, sign_name, temp_code, temp_param, cookie)


def main():
    client = Topnado()
    import random
    code = random.randint(100000, 999999)
    # client.send_register_code('13411383600', code, 'foobar')
    code = random.randint(100000, 999999)
    client.send_reset_password_code('13411383600', code, 'foobar')
    code = random.randint(100000, 999999)
    # client.send_change_phone_code('13411383600', code, 'foobar')


if '__main__' == __name__:
    main()
